{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "cf0d7310",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import openpyxl\n",
    "from openpyxl.styles import Font\n",
    "from sklearn.metrics import r2_score\n",
    "import numpy as np\n",
    "# 导入线性回归模型\n",
    "from sklearn.linear_model import LinearRegression\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "5b4ba85e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 定义函数来读取Excel文件并返回前num_rows行数据\n",
    "def read_excel_head(file_path, sheet_name='Sheet1', num_rows=10):\n",
    "    \"\"\"\n",
    "    读取Excel文件并返回前num_rows行数据。\n",
    "    \"\"\"\n",
    "    # 使用pandas读取Excel文件\n",
    "    df = pd.read_excel(file_path, sheet_name=sheet_name)\n",
    "    # 返回前num_rows行数据\n",
    "    return df.head(num_rows)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "02a7ae98",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>预测</th>\n",
       "      <th>实际</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>5.0</td>\n",
       "      <td>4.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>3.0</td>\n",
       "      <td>3.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>5.0</td>\n",
       "      <td>5.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>2.0</td>\n",
       "      <td>2.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>4.0</td>\n",
       "      <td>4.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>3.0</td>\n",
       "      <td>3.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>3.0</td>\n",
       "      <td>3.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "    预测   实际\n",
       "0  4.0  4.0\n",
       "1  0.0  0.0\n",
       "2  5.0  4.0\n",
       "3  4.0  4.0\n",
       "4  3.0  3.0\n",
       "5  5.0  5.0\n",
       "6  2.0  2.0\n",
       "7  4.0  4.0\n",
       "8  3.0  3.0\n",
       "9  3.0  3.0"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "new_file_path=r\"data.xlsx\"\n",
    "# 读取上传的Excel文件的前10行数据\n",
    "df_head = read_excel_head(new_file_path)\n",
    "df_head"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "9b4efedf",
   "metadata": {},
   "outputs": [],
   "source": [
    "def calculate_statistics(df):\n",
    "    \"\"\"\n",
    "    计算R方, RMSEP, MSE, 和 RPD。\n",
    "    假设DataFrame中包含两列，一列是实际值，另一列是预测值。\n",
    "    \"\"\"\n",
    "    # 假设第一列是预测值，第二列是实际值\n",
    "    predicted= df.iloc[:, 0]\n",
    "    actual = df.iloc[:, 1]\n",
    "\n",
    "    # 计算 R^2\n",
    "    r2 = r2_score(actual, predicted)\n",
    "\n",
    "    # 计算 MSE\n",
    "    mse = np.mean((actual - predicted) ** 2)\n",
    "\n",
    "    # 计算 RMSEP\n",
    "    rmsep = np.sqrt(mse)\n",
    "\n",
    "    # 计算 RPD\n",
    "    rpd = np.std(actual) / np.mean(actual)\n",
    "\n",
    "    return r2, rmsep, mse, rpd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "ecf29d63",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 定义一个函数来执行线性回归并返回系数a和b\n",
    "def linear_regression_coefficients(df):\n",
    "    # 假设第一列是自变量，第二列是因变量\n",
    "    X = df.iloc[:, 0].values.reshape(-1, 1)  # 预测值\n",
    "    y = df.iloc[:, 1].values  # 实际值\n",
    "\n",
    "    # 创建线性回归模型\n",
    "    model = LinearRegression()\n",
    "    # 拟合模型\n",
    "    model.fit(X, y)\n",
    "    \n",
    "    # 获取系数a和b\n",
    "    a = model.coef_[0]  # 斜率\n",
    "    b = model.intercept_  # 截距\n",
    "\n",
    "    return a, b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "8f1c303b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 使用提供的函数计算统计量\n",
    "r2, rmsep, mse, rpd = calculate_statistics(df_head)\n",
    "# 使用线性回归函数找到系数a和b\n",
    "a, b = linear_regression_coefficients(df_head)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "89c487bd",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'统计量': ['R^2', 'RMSEP', 'MSE', 'RPD'],\n",
       " '值': [0.9431818181818182, 0.31622776601683794, 0.1, 0.41457809879442503]}"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 创建一个新的DataFrame来保存整理后的数据\n",
    "统计数据 = {\n",
    "    \"统计量\": [\"R^2\", \"RMSEP\", \"MSE\", \"RPD\"],\n",
    "    \"值\": [r2, rmsep, mse, rpd]\n",
    "}\n",
    "# 创建一个新的DataFrame来保存线性回归的系数\n",
    "线性回归系数 = {\n",
    "    \"系数\": [\"a\", \"b\"],\n",
    "    \"值\": [a, b]\n",
    "}\n",
    "\n",
    "统计数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "3a83eb4d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'系数': ['a', 'b'], '值': [0.9154228855721395, 0.17910447761193993]}"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "线性回归系数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "46bd49f6",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c5cc7ede",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
